'use client'

import { useEffect, useState } from 'react'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'
import { addDays, format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

type TimeRange = 'day' | 'week' | 'month' | 'custom'
type MetricType = 'newUsers' | 'activeUsers' | 'totalUsers'

interface TrendData {
  date: string
  newUsers: number
  activeUsers: number
  totalUsers: number
}

interface Props {
  metrics: MetricType[]
  timeRange: TimeRange
  dateRange?: {
    from: Date
    to: Date
  }
}

const COLORS = {
  newUsers: '#1677FF',    // 蓝色
  activeUsers: '#52C41A', // 绿色
  totalUsers: '#FA8C16'   // 橙色
}

const metricLabels = {
  newUsers: '新增用户数',
  activeUsers: '活跃用户数',
  totalUsers: '累计用户数',
}

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

const formatDateToString = (date: Date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

export function UserTrendChart({ metrics, timeRange, dateRange }: Props) {
  const [data, setData] = useState<TrendData[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        let startDate, endDate
        const now = new Date()
        const today = formatDateToString(now)

        switch (timeRange) {
          case 'day': {
            startDate = today
            endDate = today
            break
          }
          case 'week': {
            const start = addDays(now, -6)
            startDate = formatDateToString(start)
            endDate = today
            break
          }
          case 'month': {
            const currentYear = now.getFullYear()
            const currentMonth = now.getMonth() + 1
            startDate = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-01`
            endDate = today
            break
          }
          case 'custom': {
            if (!dateRange?.from || !dateRange?.to) {
              throw new Error('请选择日期范围')
            }
            startDate = formatDateToString(dateRange.from)
            endDate = formatDateToString(dateRange.to)
            break
          }
        }

        const response = await fetch(
          `/api/user-trend?startDate=${startDate}&endDate=${endDate}`,
          {
            headers: {
              'Accept': 'application/json',
            }
          }
        )

        if (!response.ok) {
          throw new Error('获取数据失败')
        }

        const responseData = await response.json()
        setData(responseData)
      } catch (error) {
        console.error('Error fetching trend data:', error)
        setError(error instanceof Error ? error.message : '获取数据失败')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [timeRange, dateRange])

  if (error) {
    return (
      <div className="h-[400px] flex items-center justify-center text-red-500">
        {error}
      </div>
    )
  }

  if (loading) {
    return (
      <div className="h-[400px] flex items-center justify-center">
        加载中...
      </div>
    )
  }

  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-white p-3 shadow-lg rounded-lg border">
          <p className="font-medium mb-2">
            {format(new Date(label), 'yyyy年MM月dd日', { locale: zhCN })}
          </p>
          {payload.map((entry: any) => (
            <p key={entry.name} className="text-sm" style={{ color: entry.color }}>
              {metricLabels[entry.name as MetricType]}: {formatNumber(entry.value)}
            </p>
          ))}
        </div>
      )
    }
    return null
  }

  return (
    <div className="h-[400px] mt-6">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={data}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis 
            dataKey="date" 
            tickFormatter={(value) => format(new Date(value), 'MM-dd')}
          />
          <YAxis />
          <Tooltip content={<CustomTooltip />} />
          <Legend 
            formatter={(value) => metricLabels[value as MetricType]}
          />
          {metrics.map(metric => (
            <Line
              key={metric}
              type="monotone"
              dataKey={metric}
              name={metric}
              stroke={COLORS[metric]}
              strokeWidth={2}
              dot={{ r: 4 }}
              activeDot={{ r: 6 }}
            />
          ))}
        </LineChart>
      </ResponsiveContainer>
    </div>
  )
} 